package com.wu.utils;

import com.wu.pojo.po.userPo.User;
import io.jsonwebtoken.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * JWT工具类
 */
@Data
@Component
@Slf4j
//@ConfigurationProperties(prefix = "markerhub.jwt")
public class JwtUtils {

    private static final String SECRET = "f4e2e52034348f86b67cde581c0f9eb5";
    private static final long EXPIRE_TIME = 1000*60*50;  //过期时间50分钟
    private static final String HEADER = "token";

    /**
     * 生成jwt token
     */
    public String generateToken(User user) {
        if( user.getId() == null || user.getUsername() == null){
            return null;
        }
        String token = Jwts.builder()
                .setHeaderParam("typ","JWT")
                .setSubject(user.getId()+"")
                .claim("userId",user.getId())
                .claim("username",user.getUsername())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis()+EXPIRE_TIME ))
                .signWith(SignatureAlgorithm.HS256,SECRET)
                .compact();

        return token;
    }

    // 获取jwt的信息
    public static Claims getClaimByToken(String token) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody();
            return claims;
        } catch (Exception e) {
            log.debug("validate is token error", e);
            return null;
        }
    }

    /**
     * token是否过期
     *
     * @return true：过期
     */
    public boolean isTokenExpired(Date expiration) {
        return expiration.before(new Date());
    }
}
